package org.linlinjava.litemall.admin.web2.auth;


import com.github.pagehelper.PageHelper;
import com.google.common.collect.HashBiMap;
import io.swagger.annotations.*;
import org.linlinjava.litemall.admin.service2.ABaseService;
import org.linlinjava.litemall.admin.web2.auth.req.AReq;
import org.linlinjava.litemall.admin.web2.auth.req.AReq2;
import org.linlinjava.litemall.admin.web2.auth.req.AReq3;
import org.linlinjava.litemall.admin.web2.auth.req.AReq4;
import org.linlinjava.litemall.admin.web2.auth.resp.AResp;
import org.linlinjava.litemall.admin.web2.auth.resp.AResp2;
import org.linlinjava.litemall.admin.web2.auth.resp.AResp3;
import org.linlinjava.litemall.admin.web2.auth.resp.AResp4;
import org.linlinjava.litemall.admin.web2.user.resp.UResp1;
import org.linlinjava.litemall.core.util.R;
import org.linlinjava.litemall.core.util.Util;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.enumeration.Const;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.linlinjava.litemall.db.util.Str;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 权限管理
 */
@Api("权限管理")
@RestController
@RequestMapping("/auth/")
public class AuthController {


    @ApiOperation(value = "管理员管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", paramType = "query"),
            @ApiImplicitParam(name = "size", paramType = "query")
    })
    @GetMapping("/adminList")
    @ApiResponses({@ApiResponse(response = AResp.class, message = "正常响应", code = 200)
    })
    public Object adminList(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer size) {
        PageHelper.startPage(page, size);
        List<LitemallAdmin> adminList = adminMapper.selectByExample(LitemallAdminExample.newAndCreateCriteria().example());
        List<AResp> list = Util.pageList(adminList);
        adminList.forEach(a -> {
            AResp vo = new AResp(a);
            vo.pushShop(shopMapper.selectByPrimaryKey((a.getShopId())));
            list.add(vo);
        });
        return R.okList(list);
    }

    @ApiOperation(value = "管理员详情")
    @GetMapping("/get")
    @ApiResponses({@ApiResponse(response = AResp2.class, message = "正常响应", code = 200)
    })
    public Object get(@RequestParam Integer id) {
        LitemallAdmin oldAdmin = adminService.findAdmin(id);
        AResp2 vo = new AResp2(oldAdmin);
        return R.ok(vo);
    }

    @ApiOperation(value = "下拉框[选择商铺]")
    @GetMapping("/shopList")
    public Object shopList() {
        List<TShop> shops = shopMapper.selectByExample(TShopExample.newAndCreateCriteria().example());
        List<UResp1> voList = Util.aList(shops.size());
        voList.add(new UResp1(0, "平台"));
        shops.forEach(s -> voList.add(new UResp1(s.getId(), s.getShopName())));
        return R.ok(voList);
    }


    @ApiOperation(value = "重置管理员密码")
    @PostMapping("/resetPwd")
    public Object resetPwd(@RequestBody AReq2 req) {
        LitemallAdmin admin = adminService.findAdmin(req.getId());
        //设置密码
        String rawPassword = req.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        admin.setPassword(encodedPassword);
        adminService.updateById(admin);
        return R.ok("重置成功!");
    }

    @ApiOperation(value = "新增管理员")
    @PostMapping("/saveAdmin")
    public Object saveAdmin(@RequestBody AReq req) {
        if (req.getId() == null)
            return add(req);
        else
            return update(req);
    }

    @ApiOperation(value = "删除管理员")
    @PostMapping("/delAdmin")
    public Object delAdmin(@RequestBody AReq4 req) {
        String[] ids = req.getIds().split(",");
        for (String id : ids) {
            int _id = Integer.parseInt(id);
            if (_id == 1)
                continue;
            adminMapper.deleteByPrimaryKey(_id);
        }
        return R.ok("删除成功");
    }

    private Object add(AReq req) {
        List<LitemallAdmin> list = adminService.findAdmin(req.getUsername());
        if (list.size() > 0)
            return R.fail("登录账号已经存在，不能重复!");

        LitemallAdmin admin = req.getEntity(req);
        Integer shopId = admin.getShopId();
        if (shopId != null) {
            log.info("处理头像");
            TUser2 user2 = user2Mapper.selectOneByExample(TUser2Example.newAndCreateCriteria().andSIdEqualTo(shopId).example());
            if (user2 != null) {
                TUserInfo userInfo = userInfoMapper.selectOneByExample(TUserInfoExample.newAndCreateCriteria().andUser2IdEqualTo(user2.getId()).example());
                admin.setAvatar(userInfo.getAvatar());
            }
        }
        if (Str.isEmpty(admin.getAvatar())) {
            log.info("设置管理员默认头像");
            admin.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }
        Integer[] roleId = {1}; //直接就是超级管理员
        admin.setRoleIds(roleId);
        adminService.add(admin);
        return R.ok("添加成功");
    }


    private Object update(AReq req) {
        LitemallAdmin oldAdmin = adminService.findAdmin(req.getId());

        LitemallAdmin admin = req.getEntity(req);
        admin.setUsername(oldAdmin.getUsername());
        admin.setAddTime(oldAdmin.getAddTime());
        admin.setPassword(oldAdmin.getPassword());
        admin.setId(oldAdmin.getId());
        adminService.updateById(admin);
        return R.ok("修改成功");
    }


    @ApiOperation(value = "用户组管理")
    @GetMapping("/userRoleList")
    public Object userRoleList() {
        List<AResp4> list = Util.aList(7);
        list.add(new AResp4(Const.Identity.GOODS_MANAGER));
        list.add(new AResp4(Const.Identity.GOODS_SENDER));
        list.add(new AResp4(Const.Identity.DIRECT));
        list.add(new AResp4(Const.Identity.FRANSHISED2));
        list.add(new AResp4(Const.Identity.FRANSHISED));
        list.add(new AResp4(Const.Identity.SELFMENTION));
        list.add(new AResp4(Const.Identity.DISTRIBUTOR));
        return R.ok(list);
    }


    @ApiOperation(value = "用户组-获取权限")
    @GetMapping("/getRole")
    @ApiResponses({@ApiResponse(response = AResp3.class, message = "正常响应", code = 200)
    })
    public Object getRole(@RequestParam Integer typeId) {
        TAdminRole roleAuth = adminRoleMapper.selectByPrimaryKey(typeId);
        return R.ok(new AResp3(roleAuth));
    }

    @ApiOperation(value = "用户组-保存权限")
    @PostMapping("/saveRole")
    public Object saveRole(@RequestBody AReq3 req) {
        TAdminRole tAdminRole = adminRoleMapper.selectByPrimaryKey(req.getId());
        String[] roleAuth = req.getRoleAuth();
        if (roleAuth != null && roleAuth.length > 0)
            tAdminRole.setAuths(String.join(",", roleAuth));
        else
            tAdminRole.setAuths("");
        adminRoleMapper.updateByPrimaryKey(tAdminRole);
        return R.ok();
    }

    private Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private TAdminRoleMapper adminRoleMapper;
    @Autowired
    private LitemallAdminMapper adminMapper;
    @Autowired
    private TShopMapper shopMapper;
    @Autowired
    private LitemallAdminService adminService;
    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private TUser2Mapper user2Mapper;
}
